package cn.tedu.mall.seckill.timer.job;

import cn.tedu.mall.pojo.seckill.model.SeckillSku;
import cn.tedu.mall.pojo.seckill.model.SeckillSpu;
import cn.tedu.mall.seckill.mapper.SeckillSkuMapper;
import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SeckillInitialJob implements Job {

    @Autowired
    private SeckillSpuMapper spuMapper;
    @Autowired
    private SeckillSkuMapper skuMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        LocalDateTime time = LocalDateTime.now().plusMinutes(5);

        List<SeckillSpu> seckillSpus = spuMapper.findSeckillSpusByTime(time);

        for(SeckillSpu seckillSpu : seckillSpus){
            List<SeckillSku> seckillSkus = skuMapper.findSeckillSkuBySpuId(seckillSpu.getSpuId());
            for(SeckillSku seckillSku : seckillSkus){
                log.info("开始将{}号sku商品库存预热到Redis", seckillSku.getSkuId());
                String stockKey = SeckillCacheUtils.getStockKey(seckillSku.getSkuId());
                if(redisTemplate.hasKey(stockKey)){
                    //已经完成缓存
                    log.info("{}号sku商品库存已经缓存过了", seckillSku.getSkuId());
                    continue;
                }
                stringRedisTemplate.boundValueOps(stockKey)
                        .set(seckillSku.getSeckillStock().toString(),
//                                1000*60*60*2+1000*60*5+RandomUtils.nextInt(1000*30),
                                1000*60*5+RandomUtils.nextInt(1000*30),
                                TimeUnit.MILLISECONDS);
                log.info("{}号sku商品库存已预热到Redis", seckillSku.getSkuId());

            }
            String randCodeKey = SeckillCacheUtils.getRandCodeKey(seckillSpu.getSpuId());
            if(redisTemplate.hasKey(randCodeKey)){
                log.info("随机码【{}】存在", redisTemplate.boundValueOps(randCodeKey).get());
                return;
            }
            int randCode = RandomUtils.nextInt(9000*1000)+1000*1000;
            redisTemplate.boundValueOps(randCodeKey)
                    .set(randCode, 1000*60*5+RandomUtils.nextInt(1000*30), TimeUnit.MILLISECONDS);
            log.info("{}号spu随机码【{}】预热完成", seckillSpu.getSpuId(), randCode);
        }
    }
}
